package com.lykj.llw.box.ui.activity

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.lykj.lib_base.app.BaseApplication
import com.lykj.lib_base.base.BaseActivity
import com.lykj.lib_base.bus.FlowBus
import com.lykj.lib_base.component.GlideApp
import com.lykj.lib_base.constants.BConstants
import com.lykj.lib_base.data.bean.response.UserInfoResponse
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.utils.PackageUtils
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.databinding.ActSettingBinding
import com.lykj.llw.box.ui.diafrg.BottomPicPickerDiaFrg
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody

/**
 * ================================================
 * 设置页面
 * ================================================
 *
 * @author gosha
 * @date 2023/10/17-17:48
 */
class SettingActivity : BaseActivity() {
    lateinit var binding: ActSettingBinding

    private var isAuth = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActSettingBinding.inflate(layoutInflater)
        setContentView(binding.root)


        initUI()
        initData()
        setListener()
    }

    override fun onResume() {
        super.onResume()

        ImmersionBar.with(this)
            .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
            .navigationBarDarkIcon(true)
            .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
            .navigationBarEnable(false)
            .init()

        obtainUserInfo()
    }

    override fun initUI() {
        binding.titleBar.tvTitle.text = "设置"
        binding.titleBar.tvRightOption.visibility = View.INVISIBLE

        binding.tvVersion.text = "V${PackageUtils.getVersionName(this)}"

        FlowBus.with<String>("UpdateAvatar").register(this) {
            GlideApp.with(this@SettingActivity)
                .load(it)
                .circleCrop()
                .transition(DrawableTransitionOptions.withCrossFade())
                .into(binding.ivAvatar)
        }
    }

    //获取用户信息
    private fun obtainUserInfo() {
        RetrofitManager.instance.obtainUserInfo(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@SettingActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(responseBody, UserInfoResponse::class.java)
                binding.tvNickName.text =
                    if (bean.data?.username.isNullOrBlank()) "野原新之助" else bean.data?.nickname
                binding.tvAccount.text = "${bean.data?.username}"

                isAuth = bean.data?.isAuthName == 1

                binding.tvVerify.text = if (isAuth) "已实名" else "未认证"

                if (!bean.data?.avatar.isNullOrBlank()) {
                    GlideApp.with(this@SettingActivity)
                        .load(bean.data?.avatar)
                        .circleCrop()
                        .transition(DrawableTransitionOptions.withCrossFade())
                        .into(binding.ivAvatar)
                }
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let { LogUtils.e("$msg") }
            }
        })
    }

    //退出登录
    private fun logout() {
        RetrofitManager.instance.logout(object : CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@SettingActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                BaseApplication.instance?.clearUserInfo(false)
                ToastUtils.showShort(this@SettingActivity, "退出登录成功")
                FlowBus.with<String>(BConstants.BUS_KEY.LOGOUT_SUCCESS).post(lifecycleScope, "")

                //清除代理用户信息
                BaseApplication.instance?.clearAgentUserInfo(false)
                FlowBus.with<String>(BConstants.BUS_KEY.AGENT_LOGOUT_SUCCESS)
                    .post(lifecycleScope, "")
                finish()
            }

            override fun handleException(ret: String, msg: String?) {
                ToastUtils.showShort(this@SettingActivity, "$msg")
            }
        })
    }

    override fun initData() {
    }

    override fun setListener() {
        binding.titleBar.ivBack.clickWithTrigger {
            finish()
        }

        binding.lltAvatar.clickWithTrigger(300) {
            BottomPicPickerDiaFrg()
                .setUserType(0)
                .show(supportFragmentManager, "图片获取方式选择弹窗")
        }

        binding.lltNickName.clickWithTrigger(300) {
            startActivity(Intent(this, EditNickNameActivity::class.java))
        }

        binding.lltVerify.clickWithTrigger(300) {
            if (isAuth) {
                ToastUtils.showShort(this, "已实名")
            } else {
                startActivity(Intent(this, RealNameAuthActivity::class.java))
            }
        }

        binding.tvBtnLogout.clickWithTrigger {
            logout()
        }
    }

    override fun onDestroy() {
        removeDisposables(this)
        super.onDestroy()
    }
}